#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase
from SceneCheckTool.data import __CURRENT_PATH__

try:
    import maya.cmds as cmds
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
    import elsLibs.ShotInfoFromFile as elssif
    reload(elssif)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CheckELSAniHierachy(CheckBase):
    def __init__(self):
        super(CheckELSAniHierachy, self).__init__()
        pass

    def init_file(self):
        scene_name = mu.sceneName()
        sif = elssif.ShotInfoFromFile(scene_name)
        self.seqshot = sif.get_seqshot

    def build_group(self, data, parent=''):
        if not data:
            return
        for item in data:
            _name = item['name']
            _child = item['child']
            _desc = item['desc']
            hiera_name = '{}|{}'.format(parent, _name)
            if _name == 'Cameras':
                if cmds.objExists('|cameras'):
                    cmds.rename('|cameras', 'Cameras')
                if cmds.objExists('|Cameras'):
                    try:
                        cmds.parent('|Cameras', 'Root')
                    except:
                        pass
            if _name == 'Assets' and cmds.objExists('|Assets'):
                try:
                    cmds.parent('|Assets', 'Root')
                except:
                    pass
            if _name == 'Assets' and cmds.objExists('|assets'):
                try:
                    cmds.rename('|assets', 'Assets')
                    cmds.parent('|Assets', 'Root')
                except:
                    pass
            if _name == 'lay' and cmds.objExists('Assets|lay'):
                try:
                    cmds.parent('Assets|lay', 'Root')
                except:
                    pass
            if _name == 'fx' and cmds.objExists('Assets|fx'):
                try:
                    cmds.parent('Assets|fx', 'Root')
                except:
                    pass
            if _name == 'fx' and cmds.objExists('Assets|lay|fx'):
                try:
                    cmds.parent('Assets|lay|fx', 'Root')
                except:
                    pass
            if not cmds.objExists(hiera_name):
                if parent and cmds.objExists(parent):
                    cmds.group(em=1, n=_name, p=parent)
                else:
                    cmds.group(em=1, n=_name)

            self.build_group(_child, parent=hiera_name)

    def re_parent_type(self):
        import jarryLibs.mayakit.JFileReference as jrf
        j_ref_list = [ref for ref in jrf.listReferences(':') if ref.isLoaded()]
        # print j_ref_list
        for _ref in j_ref_list:
            if not _ref.nodes():
                continue

            top_node = _ref.nodes()[0]
            print _ref, top_node


            top_node_parent = cmds.listRelatives(top_node, p=1)
            if top_node_parent:
                top_node_parent = top_node_parent[0]

            if top_node_parent not in ['Character', 'Environment', 'Prop']:
                asset_type = _ref.path.split('/')[3]
                print asset_type, top_node
                try:
                    cmds.parent(top_node, 'Assets|{}'.format(asset_type))
                except:
                    pass
        hud_list = cmds.ls(type='jarryShotHud')
        try:
            cmds.parent(hud_list, 'Root|Cameras')
        except:
            pass
        self.init_file()
        cam_list = cmds.ls('%s_cameraShape' % self.seqshot, type='camera', long=1)
        if cam_list:
            cam_top_node = cam_list[0].split('|')[1]
            if cam_top_node != 'Root':
                try:
                    cmds.parent(cam_top_node, 'Root|Cameras')
                except:
                    pass
        else:
            raise RuntimeError(u'没有找到相机')

    def load_config(self):
        import jarryLibs.dict2json as d2j
        _dir = __CURRENT_PATH__.child('checkScript').child('Lay').child('CheckELSAniHierachy')
        data = d2j.dict2json('{}/hierarchy.json'.format(_dir)).read()
        return data

    def check(self):
        current_file = mu.sceneName()
        if not current_file:
            result_log = u'Error: 当前文件未保存!'
            return result_log
        if current_file.startswith('els_'):
            result_log = u'Error: 当前文件非els项目镜头规则!'
            return result_log
        try:
            self.init_file()
        except:
            result_log = u'Error:当前文件不符合ELS项目资产文件命名规则'
            return result_log

        if not cmds.objExists('Root|Assets'):
            result_log = u'Error:没有找到符合项目规则的层级'
        else:
            result_log = u'Succeed:没有问题'
        return result_log

    def fix(self):
        data = self.load_config()
        # print data
        self.build_group(data, '')
        self.re_parent_type()
        return self.check()